package com.ttb.smshelper;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import com.ttb.blocksms.BlockService;
import com.ttb.database.Schedule;
import com.ttb.database.ScheduleDAO;
import com.ttb.smshelper.DayOfWeek.Day;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable.Callback;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class lichmessage extends Activity {
	TextView txtDate, txtTime, txtloop;
	EditText editnoidung, editphone;
	Button btnDate, btnTime, btnthemlich, btnloop;
	TableLayout tableFunction;
	TableRow tableDate, tableTime;
	ArrayList<list_lich> arrLich = new ArrayList<list_lich>();
	ArrayAdapter<list_lich> adapter = null;
	ListView lvlichgui;
	Calendar cal;
	Date dateFinish;
	Date hourFinish;
	BlockService schedule;
	Calendar calendarTrigger;
	private int triggerYear;
	private int triggerMonth;
	private int triggerDay;
	private int triggerHour;
	private int triggerMinute;
	private Boolean dateSet;
	private Boolean hourSet;
	private String[] dayofweek = new String[] { "Monday", "Tuesday",
			"Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
	private final String[] menuList = { "Once", "Daily", "Weekly", "Monthly",
			"Yearly" };
	private int mYear;
	private int mMonth;
	private int mDay;
	private String choosenDayOfWeek;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.manhinh_lich);
		loadTabs();
		doFormWidgets();
		getDefaultInfor();
		addEventFormWidgets();
	}

	private void doFormWidgets() {
		txtDate = (TextView) findViewById(R.id.txtdate);
		txtTime = (TextView) findViewById(R.id.txttime);
		editnoidung = (EditText) findViewById(R.id.editnoidung);
		editphone = (EditText) findViewById(R.id.editphone);
		btnDate = (Button) findViewById(R.id.btndate);
		btnTime = (Button) findViewById(R.id.btntime);
		btnthemlich = (Button) findViewById(R.id.btnthemlich);
		lvlichgui = (ListView) findViewById(R.id.lvlichgui);
		adapter = new ArrayAdapter<list_lich>(this,
				android.R.layout.simple_list_item_1, arrLich);
		lvlichgui.setAdapter(adapter);
		txtloop = (TextView) findViewById(R.id.txtloop);
		btnloop = (Button) findViewById(R.id.btnloop);
		tableDate = (TableRow) findViewById(R.id.tableRow3);
		tableTime = (TableRow) findViewById(R.id.tableRow4);
		tableFunction = (TableLayout) findViewById(R.id.tableFunction);
	}

	private void addEventFormWidgets() {
		btnDate.setOnClickListener(new MyButtonEvent());
		btnTime.setOnClickListener(new MyButtonEvent());
		btnthemlich.setOnClickListener(new MyButtonEvent());
		lvlichgui.setOnItemClickListener(new MyListViewEvent());
		lvlichgui.setOnItemLongClickListener(new MyListViewEvent());
		btnloop.setOnClickListener(new MyButtonEvent());
	}

	private class MyButtonEvent implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btndate:
				if (txtloop.getText().toString() == "Weekly") {
					showdayofweek();
				} else {
					showDatePickerDialog();
				}
				break;
			case R.id.btntime:
				showTimePickerDialog();
				break;
			case R.id.btnthemlich:
				processAddJob();
				break;
			case R.id.btnloop:
				showloop();
			}
		}

	}

	private class MyListViewEvent implements OnItemClickListener,
			OnItemLongClickListener {
		private int yesOrNo;

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				final int arg2, long arg3) {
			final AlertDialog.Builder b = new AlertDialog.Builder(
					lichmessage.this);
			b.setIcon(android.R.drawable.ic_dialog_alert);
			b.setTitle("Delete");
			b.setMessage("Are you sure?");
			b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					yesOrNo = 1;
					arrLich.remove(arg2);
					adapter.notifyDataSetChanged();

				}
			});
			b.setNegativeButton("Send now",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog,
								int whichButton) {
							yesOrNo = 0;
						}
					});

			b.show();
			return false;

		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {

			Toast.makeText(lichmessage.this, arrLich.get(arg2).getDesciption(),
					Toast.LENGTH_LONG).show();
		}

	}

	private void getDefaultInfor() {
		txtloop.setText("Once");
		cal = Calendar.getInstance();
		SimpleDateFormat dft = null;
		dft = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
		String strDate = dft.format(cal.getTime());
		txtDate.setText(strDate);
		dft = new SimpleDateFormat("hh:mm a", Locale.getDefault());
		String strTime = dft.format(cal.getTime());
		txtTime.setText(strTime);
		dft = new SimpleDateFormat("HH:mm", Locale.getDefault());
		txtTime.setTag(dft.format(cal.getTime()));
		editphone.requestFocus();
		dateFinish = cal.getTime();
		hourFinish = cal.getTime();
		dateSet = false;
		hourSet = false;

	}

	public void showDatePickerDialog() {
		OnDateSetListener callback = new OnDateSetListener() {
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {

				String repetition = txtloop.getText().toString();
				if (repetition.equals("Monthly")) {
					txtDate.setText(dayOfMonth + "/" + repetition);
				} else if (repetition.equals("Yearly"))
				{
					txtDate.setText((dayOfMonth) + " - " + (monthOfYear + 1) + "/" + repetition);
				}
				else {
					txtDate.setText((dayOfMonth) + "/" + (monthOfYear + 1)
							+ "/" + year);
				}

				cal.set(year, monthOfYear, dayOfMonth);
				dateFinish = cal.getTime();
				dateSet = true;
				triggerYear = year;
				triggerMonth = monthOfYear;
				triggerDay = dayOfMonth;

			}
		};
		int ngay = cal.get(Calendar.DATE);
		int thang = cal.get(Calendar.MONTH);
		int nam = cal.get(Calendar.YEAR);
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH);
		mDay = cal.get(Calendar.DATE);
		DatePickerDialog pic;
		if (txtloop.getText().toString() == "Monthly") {
			pic = this.customDatePicker(callback);
		} else {
			pic = new DatePickerDialog(lichmessage.this, callback, nam, thang,
					ngay);
		}
		pic.setTitle("Set Date");
		pic.show();
		/*
		 * remove month and year on datepicker when user choose repetition is
		 * monthly
		 */
		if (txtloop.getText().toString() == "Monthly") {
			DatePicker dp = findDatePicker((ViewGroup) pic.getWindow()
					.getDecorView());
			if (dp != null) {
				((ViewGroup) dp.getChildAt(0)).getChildAt(0).setVisibility(
						View.GONE);
				((ViewGroup) dp.getChildAt(0)).getChildAt(2).setVisibility(
						View.GONE);
			}
		}
	}

	public void showTimePickerDialog() {
		OnTimeSetListener callback = new OnTimeSetListener() {
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

				String s = hourOfDay + ":" + minute;
				int hourTam = hourOfDay;
				if (hourTam > 12)
					hourTam = hourTam - 12;
				txtTime.setText(hourTam + ":" + minute
						+ (hourOfDay > 12 ? " PM" : " AM"));

				txtTime.setTag(s);

				cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
				cal.set(Calendar.MINUTE, minute);
				hourSet = true;
				hourFinish = cal.getTime();
				triggerHour = hourOfDay;
				triggerMinute = minute;
			}
		};

		String s = txtTime.getTag() + "";
		String strArr[] = s.split(":");
		int gio = Integer.parseInt(strArr[0]);
		int phut = Integer.parseInt(strArr[1]);
		TimePickerDialog time = new TimePickerDialog(lichmessage.this,
				callback, gio, phut, true);
		time.setTitle("Set Time");
		time.show();
	}

	public void processAddJob() {
		String phone_list = editphone.getText() + "";
		String message = editnoidung.getText() + "";
		String repetition = txtloop.getText().toString();
		long triggerTime = 0;
		if (dateSet && hourSet) {
			cal.set(triggerYear, triggerMonth, triggerDay, triggerHour,
					triggerMinute, 0);
			triggerTime = cal.getTimeInMillis();
		} else {
			triggerTime = cal.getTimeInMillis();
		}

		Log.d("date time set", String.valueOf(triggerTime));

		list_lich lich = new list_lich(phone_list, message, dateFinish,
				hourFinish);
		arrLich.add(lich);
		adapter.notifyDataSetChanged();
		// editphone.setText("");
		// editnoidung.setText("");
		editphone.requestFocus();
		// validate time
		long currentTime = System.currentTimeMillis();
		Boolean error = false;
		if (phone_list == "") {
			showError("Please input a number phone.");
			editphone.requestFocus();
			error = true;
		}
		if (message == "" && !error) {
			showError("Please input your message.");
			editnoidung.requestFocus();
			error = true;

		}
		if (triggerTime < currentTime && !error) {
			showError("Please re-input a correct time.");
			error = true;
		}
		// save schedule to db
		if (!error) {

			ScheduleDAO scheduledao = new ScheduleDAO(
					this.getApplicationContext());
			scheduledao.open();

			Schedule newSchedule = scheduledao.createSchedule(phone_list,
					message, triggerTime, repetition);
			scheduledao.close();
			schedule = new BlockService();
			if (schedule != null) {
				schedule.SetAlarm(this.getApplicationContext(), newSchedule);
			} else {
				Toast.makeText(this.getApplicationContext(), "Alarm is null",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	public void loadTabs() {
		final TabHost tab = (TabHost) findViewById(android.R.id.tabhost);
		tab.setup();
		TabHost.TabSpec spec;
		spec = tab.newTabSpec("t1");
		spec.setContent(R.id.tab1);
		spec.setIndicator("New");
		tab.addTab(spec);
		spec = tab.newTabSpec("t2");
		spec.setContent(R.id.tab2);
		spec.setIndicator("Schedule List");
		tab.addTab(spec);

		tab.setCurrentTab(0);

		tab.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
			public void onTabChanged(String arg0) {
				String s = "Tab tag =" + arg0 + "; index ="
						+ tab.getCurrentTab();
			}
		});

	}

	public void showdayofweek() {
		android.app.AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Choice a day");
		builder.setItems(dayofweek, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				txtDate.setText(dayofweek[which] + "/Weekly");
				choosenDayOfWeek = dayofweek[which];
				dateSet = true;
				Log.d("choosenDayOfWeek", choosenDayOfWeek);
				switch (Day.valueOf(choosenDayOfWeek)) {
				case Sunday:
					cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
					break;
				case Monday:
					cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
					break;
				case Tuesday:
					cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
					break;
				case Wednesday:
					cal.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
					break;
				case Thursday:
					cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
					break;
				case Friday:
					cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
					break;
				case Saturday:
					cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
					break;
				}
				Log.d("trigger time", cal.getTime().toString());
				dialog.dismiss();
			}
		});
		builder.setNegativeButton("cancel",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	public void showloop() {

		final AlertDialog.Builder menuAleart = new AlertDialog.Builder(
				lichmessage.this);

		menuAleart.setTitle("Loop Type");
		menuAleart.setItems(menuList, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				switch (item) {
				case 0:
					txtloop.setText(menuList[0]);
					tableFunction.removeView(tableDate);
					/*
					 * Thien Binh note : add row with index change this index
					 * when add more layout
					 */
					tableFunction.addView(tableDate, 3);
					break;
				case 1:
					txtloop.setText(menuList[item]);
					tableFunction.removeView(tableDate);
					break;
				case 2:
					txtloop.setText(menuList[item]);
					tableFunction.removeView(tableDate);
					tableFunction.addView(tableDate, 3);
					break;
				case 3:
					txtloop.setText(menuList[item]);
					tableFunction.removeView(tableDate);
					tableFunction.addView(tableDate, 3);
				case 4:
					txtloop.setText(menuList[item]);
					tableFunction.removeView(tableDate);
					tableFunction.addView(tableDate, 3);
				}
			}
		});
		AlertDialog menuDrop = menuAleart.create();
		menuDrop.show();
	}

	public void showError(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Error");
		builder.setMessage(message);
		builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		AlertDialog errorDialog = builder.create();
		errorDialog.show();
	}


	private MyDatePickerDialog customDatePicker(OnDateSetListener callback) {
		MyDatePickerDialog dpd = new MyDatePickerDialog(this, callback,
				mYear, mMonth, mDay);
		return dpd;
	}

	public class MyDatePickerDialog extends DatePickerDialog {
		private CharSequence title;

		public MyDatePickerDialog(Context context, int theme,
				OnDateSetListener callBack, int year, int monthOfYear,
				int dayOfMonth) {
			super(context, theme, callBack, year, monthOfYear, dayOfMonth);
			// TODO Auto-generated constructor stub
		}

		public MyDatePickerDialog(Context context, OnDateSetListener callBack,
				int year, int monthOfYear, int dayOfMonth) {

			super(context, callBack, year, monthOfYear, dayOfMonth);
			// TODO Auto-generated constructor stub
		}

		public void setPermanentTitle(CharSequence title) {
			this.title = title;
			setTitle(title);
		}

		@Override
		public void onDateChanged(DatePicker view, int year, int month, int day) {
			super.onDateChanged(view, year, month, day);
			setTitle(title);
		}

	}

	private DatePicker findDatePicker(ViewGroup group) {
		if (group != null) {
			for (int i = 0, j = group.getChildCount(); i < j; i++) {
				View child = group.getChildAt(i);
				if (child instanceof DatePicker) {
					return (DatePicker) child;
				} else if (child instanceof ViewGroup) {
					DatePicker result = findDatePicker((ViewGroup) child);
					if (result != null)
						return result;
				}
			}
		}
		return null;

	}

}
